<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="100px" @submit.prevent>
      <el-form-item label="载具类型" prop="containerName">
        <el-input
          v-model.trim="queryParams.containerName"
          placeholder="请输入载具类型"
          clearable
          @keyup.enter="handleQuery"
          style="width: 175px"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['system:type:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:type:remove']"
        >批量删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['system:type:export']"
        >导出</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Download"
          @click="downloadContainerType"
        >下载导入模板</el-button>
      </el-col>
      <el-col :span="1.5">
        <MyUpload
          buttonName="导入载具类型" 
          url="/api/containerType/import"
          @success="handleUploadSuccess"
          @warning="handleUploadWarning"
        />
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>
    <TableScrollContainer :topHeight="220">
      <template #default="{ tableHeight }">
    <el-table v-loading="loading" :data="typeList" @selection-change="handleSelectionChange" :height="tableHeight" border>
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="载具类型" align="center" prop="containerName" />
      <el-table-column label="载具分类" align="center" prop="containerCategory">
        <template #default="scope">
          <dict-tag :options="category_status" :value="scope.row.containerCategory"/>
        </template>
      </el-table-column>
      <el-table-column label="长度" align="center" prop="length" /> 
      <el-table-column label="宽度" align="center" prop="width" />
      <el-table-column label="高度" align="center" prop="height" />
      <el-table-column label="单位" align="center" prop="unit" />
      <el-table-column label="隔板类型" align="center" prop="isDivided">
        <template #default="scope">
          <dict-tag :options="split_status" :value="scope.row.isDivided"/>
        </template>
      </el-table-column>
      <el-table-column label="激光灯型" align="center" prop="lightArrayCount">
        <template #default="scope">
          <dict-tag :options="light_status" :value="scope.row.lightArrayCount"></dict-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="190" fixed="right">
        <template #default="scope">
          <el-button type="success" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['system:type:edit']">修改</el-button>
          <el-button type="danger" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['system:type:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page-sizes="[10, 30, 50, 100]"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
      </template>
    </TableScrollContainer>

    <!-- 添加或修改载具类型对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" :close-on-click-modal="false">
      <el-form ref="typeRef" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="载具类型" prop="containerName">
          <el-input v-model="form.containerName" placeholder="请输入载具类型" />
        </el-form-item>
        <el-form-item label="载具分类" prop="containerCategory">
           <el-select v-model="form.containerCategory" placeholder="请选择载具分类">
             <el-option
               v-for="item in category_status"
               :key="item.value"
               :label="item.label"
               :value="Number(item.value)"
             />
           </el-select>
        </el-form-item>
        <el-form-item label="长度" prop="length">
          <el-input @input="handleNumberInput('length')" v-model.number="form.length" placeholder="请输入长度" />
        </el-form-item>
        <el-form-item label="宽度" prop="width">
          <el-input @input="handleNumberInput('width')" v-model.number="form.width" placeholder="请输入宽度" />
        </el-form-item>
        <el-form-item label="高度" prop="height">
          <el-input @input="handleNumberInput('height')" v-model.number="form.height" placeholder="请输入高度" />
        </el-form-item>
        <el-form-item label="单位" prop="unit">
           <el-select v-model="form.unit" clearable placeholder="请选择单位">
             <el-option
               v-for="item in unitList"
               :key="item.value"
               :label="item.value"
               :value="item.value"
             />
           </el-select>
        </el-form-item>
        <el-form-item label="隔板类型" prop="isDivided">
          <el-select
            v-model="form.isDivided"
            placeholder="请选择隔板类型"
            filterable
            clearable
            @change="handleDividedChange"
          >
            <el-option
              v-for="item in split_status"
              :key="item.value"
              :label="item.label"
              :value="Number(item.value)"
            />
          </el-select>
        </el-form-item>
        <!-- 只有当选择可分割时才显示激光灯型 -->
        <el-form-item 
          label="激光灯型" 
          prop="lightArrayCount" 
          v-if="form.isDivided === 1"
        >
          <el-select
            v-model="form.lightArrayCount"
            placeholder="请选择激光灯型"
            filterable
            clearable
          >
            <el-option
              v-for="item in light_status"
              :key="item.value"
              :label="item.label"
              :value="Number(item.value)"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="ContainerType">
import { listType, getType, delType, addType, updateType } from "@/api/work/containerType"
import TableScrollContainer from '@/components/Pagetable/TableScrollContainer.vue'
const { proxy } = getCurrentInstance()
const { split_status, category_status, light_status } = proxy.useDict('split_status', 'category_status', 'light_status')

const typeList = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("")
const lightArrayCountList = ref([{value: 20}, {value: 50}, {value: '无'}])
const unitList = ref([{value: 'mm'}, {value: 'cm'}, {value: 'm'}])

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    containerName: null
  },
  rules: {
    containerCategory: [
      { required: true, message: "载具分类不能为空", trigger: "blur" }
    ],
    unit: [
      { required: true, message: "单位不能为空", trigger: "blur" }
    ],
    isDivided: [
      { required: true, message: "隔板类型不能为空", trigger: "blur" }
    ],
    containerName: [
      { required: true, message: "载具类型名称不能为空", trigger: "blur" }
    ],
    length: [
      { required: true, message: '请输入长度', trigger: 'blur' },
      { 
        validator: (rule, value, callback) => {
          if (value < 1 || value > 2000) {
            callback(new Error('请输入1-2000之间的数值'));
          } else {
            callback();
          }
        },
        trigger: 'blur'
      }
    ],
    width: [
      { required: true, message: '请输入宽度', trigger: 'blur' },
      { 
        validator: (rule, value, callback) => {
          if (value < 1 || value > 2000) {
            callback(new Error('请输入1-2000之间的数值'));
          } else {
            callback();
          }
        },
        trigger: 'blur'
      }
    ],
    height: [
      { required: true, message: '请输入高度', trigger: 'blur' },
      { 
        validator: (rule, value, callback) => {
          if (value < 1 || value > 2000) {
            callback(new Error('请输入1-2000之间的数值'));
          } else {
            callback();
          }
        },
        trigger: 'blur'
      }
    ],
    // 只有当可分割时才验证激光灯型
    lightArrayCount: [
      { 
        required: true, 
        message: '请选择激光灯型', 
        trigger: 'blur',
        validator: (rule, value, callback) => {
          // 只有当选择可分割时才验证
          if (data.form.isDivided === 1 && (!value && value !== 0)) {
            callback(new Error('请选择激光灯型'));
          } else {
            callback();
          }
        }
      }
    ]
  }
})

const { queryParams, form, rules } = toRefs(data)

/** 查询载具类型列表 */
function getList() {
  loading.value = true
  listType(queryParams.value).then(res => {
    if (res.errCode === '1') {
      typeList.value = res.data.page.records
      total.value = res.data.page.total
      loading.value = false
    }
  })
}

// 取消按钮
function cancel() {
  open.value = false
  reset()
}

// 表单重置
function reset() {
  form.value = {
    containerTypeId: null,
    containerName: null,
    length: null,
    width: null,
    height: null,
    unit: null,
    createdBy: null,
    updateBy: null,
    updateTime: null,
    createTime: null,
    isDivided: null,
    lightArrayCount: null
  }
  proxy.resetForm("typeRef")
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef")
  handleQuery()
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.containerTypeId)
  single.value = selection.length != 1
  multiple.value = !selection.length
}

/** 新增按钮操作 */
function handleAdd() {
  reset()
  open.value = true
  title.value = "添加载具类型"
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset()
  const _containerTypeId = row.containerTypeId || ids.value
  getType(_containerTypeId).then(res => {
    form.value = res.data.containerType
    open.value = true
    title.value = "修改载具类型"
  })
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["typeRef"].validate(valid => {
    if (valid) {
      // 如果不可分割，清空激光灯型值
      if (form.value.isDivided !== 1) {
        form.value.lightArrayCount = null
      }
      
      if (form.value.containerTypeId != null) {
        updateType(form.value).then(res => {
          if (res.errCode === '1') {
            proxy.$modal.msgSuccess("修改成功")
            open.value = false
            getList()
          } else {
            proxy.$modal.msgError(res.msg)
          }
        })
      } else {
        addType(form.value).then(res => {
          if (res.errCode === '1') {
            proxy.$modal.msgSuccess("新增成功")
            open.value = false
            getList()
          } else {
            proxy.$modal.msgError(res.msg)
          }
        })
      }
    }
  })
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _containerTypeIds = row.containerTypeId || ids.value
  proxy.$modal.confirm('是否确认删除载具类型编号为"' + _containerTypeIds + '"的数据项？').then(function() {
    return delType(_containerTypeIds)
  }).then(res => {
    if (res.errCode === '1') {
      getList()
      proxy.$modal.msgSuccess(res.msg)
    } else {
      proxy.$modal.msgError(res.msg)
    }
  }).catch(() => {})
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('/api/containerType/export', {
    ...queryParams.value
  }, `载具类型数据_${new Date().getTime()}.xlsx`)
}

// 下载模板
const downloadContainerType = async() => {
  proxy.download('/api/containerType/downloadTemplate', {}, `载具类型模板_${new Date().getTime()}.xlsx`)
}

// 上传成功后的回调
const handleUploadSuccess = (res) => {
  getList()
}

// 部分成功回调
const handleUploadWarning = (res) => {
  getList()
}

// 处理是否可分割变更
const handleDividedChange = (value) => {
  // 当选择不可分割时，清空激光灯型值
  if (value !== 1) {
    form.value.lightArrayCount = null
  }
}

getList()

const handleNumberInput = (key) => {
  form.value[key] = form.value[key]
    .toString()
    .replace(/[^\d.]/g, '')
    .replace(/\.{2,}/g, '.')
    .replace(/^\./, '')
}
</script>
